package com.ning.run.common.utils;


import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Date;
import java.util.Properties;

/**
 * @Description: 邮箱工具类,使用前先填好常量
 * @param: null
 * @return
 * @author: ning
 * @email: cxy_ning@163.com
 * @date: 2022/12/15 20:00
*/
public class MailUtil {
    //使用哪个邮箱进行发送
    private static final String email = "";

    //邮箱密码
    private static final String password = "";

    //邮箱中发送人的姓名
    private static final String nickname = "Run Community";
    /**
     * 发送邮件
     * @param emailPassword email的授权码
     * @param receiver 接收人
     * @param nickname 向接收人显示的昵称
     * @param sender 发送人
     * @param messageNumber 验证码
     * @throws Exception
     */
    public static void sendEmails(String emailPassword, String sender, String receiver , String messageNumber, String nickname) throws Exception{

        Properties props = new Properties();

        props.setProperty("mail.smtp.auth","true");
        //传输方式
        props.setProperty("mail.transport.protocol","smtp");
        //使用的服务器网易的服务器，也可以使用QQ的
        props.setProperty("mail.smtp.host", "smtp.163.com");

        Session session = Session.getInstance(props);

        session.setDebug(true);

        Transport transport = session.getTransport();

        transport.connect(sender, emailPassword);

        Message message = createMessage(session, receiver, nickname, sender, messageNumber);

        transport.sendMessage(message, message.getAllRecipients());

        transport.close();

    }

    /**
     * 创建一封邮件
     * @param session
     * @param receiver 接收人
     * @param nickname 向接收人显示的昵称
     * @param sender 发送人
     * @param messageNumber 验证码
     * @return 返回一个邮件
     * @throws Exception
     */
    public static MimeMessage createMessage (Session session, String receiver, String nickname, String sender, String messageNumber) throws Exception{

        MimeMessage message=new MimeMessage(session);

        message.setFrom(new InternetAddress(nickname + "<" + sender + ">"));

        message.setRecipient(RecipientType.TO, new InternetAddress(receiver));

        message.setSubject("邮件主题");

        message.setContent("账号新密码为：" + messageNumber, "text/html;charset=UTF-8");

        message.setSentDate(new Date());

        return message;
    }
    //参数列表 接受人邮箱，发送的信息
    /**
     * @Description: 调用该方法，就可以向指定邮箱发送邮件
     * @param: receiver 接受人邮箱
     * @param: messageNumber 验证码
     * @return void
     * @author: ning
     * @email: cxy_ning@163.com
     * @date: 2022/12/15 19:52
    */
    public static void sendEmails(String receiver , String messageNumber) throws Exception{

        sendEmails(password,email,receiver,messageNumber,nickname);
    }
}
